/*
 * Copyright 2003-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.edu.tsinghua.cic.ccss.task;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;
import org.forten.mail.template.FreeMarkerBean;
import org.forten.utils.common.DateUtil;
import org.forten.utils.common.NumberUtil;
import org.forten.utils.system.LogUtil;
import org.springframework.stereotype.Component;

import cn.edu.tsinghua.cic.ccss.bo.CourseBo;
import cn.edu.tsinghua.cic.ccss.bo.SystemSettingBo;
import cn.edu.tsinghua.cic.ccss.dto.SendMessageToCadreDto;

/**
 * 
 * 
 * @author <a href="mailto:du_yi@bbn.cn">Duyi</a>
 * @since 2012-5-19
 */
@Component("sendMailToCadreTask")
public class SendMailToCadreTask {
	private static Logger log = Logger.getLogger(SendMailToCadreTask.class);

	@Resource
	private CourseBo courseBo;
	@Resource(name = "systemSettingBo")
	private SystemSettingBo systemSettingBo;
	@Resource
	private FreeMarkerBean freeMarkerBean;
	@Resource
	private EhcacheUtil ehcacheUtil;

	public void sendMail() throws EmailException, AddressException {
		try {
			Thread.sleep(NumberUtil.getRandomInteger(1, 30000));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		LogUtil.info(log, "mailFlag is : %d", ehcacheUtil.getFlag("mailFlag"));
		if (ehcacheUtil.getFlag("mailFlag") != 0) {
			// ehcacheUtil.setFlag("mailFlag", 0);
			return;
		} else {
			ehcacheUtil.setFlag("mailFlag", 1);
			LogUtil.info(log, "于%s准备执行向干部发送开课通知邮件任务",
					DateUtil.convertDateToString(new Date()));
			List<SendMessageToCadreDto> dtoList = courseBo
					.querySendMailToCadreDto();
			for (SendMessageToCadreDto dto : dtoList) {
				Email email = initEmailHost();
				email.setSubject(dto.getName() + "-开课通知");
				InternetAddress[] adds = InternetAddress.parse(dto
						.getCadreEmails());
				email.setTo(Arrays.asList(adds));
				Map<String, SendMessageToCadreDto> data = new HashMap<String, SendMessageToCadreDto>();
				data.put("dto", dto);
				email.setMsg(freeMarkerBean.getTemplateContent(
						"to_students_email.ftl", data));

				email.send();
			}
			LogUtil.info(log, "于%s完成为干部发送开课通知邮件任务",
					DateUtil.convertDateToString(new Date()));
		}
	}

	private Email initEmailHost() throws EmailException {
		Email email = new HtmlEmail();
		email.setCharset("UTF-8");
		email.setHostName(systemSettingBo.getStringValue("EMAIL_HOST_NAME"));
		email.setAuthenticator(new DefaultAuthenticator(systemSettingBo
				.getStringValue("EMAIL_USERNAME"), systemSettingBo
				.getStringValue("EMAIL_PASSWORD")));
		email.setFrom(systemSettingBo.getStringValue("EMAIL_FROM"));
		return email;
	}
}
